//测试排序
// pnpm i @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities
import {
  DndContext,
  useSensors,
  DragEndEvent,
  closestCenter,
  PointerSensor,
  KeyboardSensor,
  useSensor,
} from '@dnd-kit/core';
import {
  sortableKeyboardCoordinates,
  arrayMove,
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { useState } from 'react';
import Item from './item';
type ComponentType = {
  id: string;
  title: string;
};
const Container = () => {
  // const [items, setItems] = useState(['alex', 'sam', 'arden']);
  const [comItems, setComItems] = useState<ComponentType[]>([
    { id: '1', title: 'alex' },
    { id: '2', title: 'alex2' },
    { id: '3', title: 'alex3' },
  ]);
  const sensors = useSensors(
    useSensor(PointerSensor), //鼠标
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    }), //键盘
  );
  const hanlderDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over == null) return;
    if (active.id !== over.id) {
      setComItems((items) => {
        const oldIndex = comItems.findIndex((c) => c.id === active.id);
        const newIndex = comItems.findIndex((c) => c.id === over.id);
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  };
  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={hanlderDragEnd}>
      <SortableContext items={comItems} strategy={verticalListSortingStrategy}>
        {comItems.map((c) => (
          <Item key={c.id} id={c.id} title={c.title}></Item>
        ))}
      </SortableContext>
    </DndContext>
  );
};

export default Container;
